/**
 * @desc：金额调整记录弹框
 * @author:Elvis
 *
 *
 * * */
import React, { useState, useEffect } from 'react';
import { Button, Form, Input, DatePicker, Select, Tooltip } from 'antd';
import CommonModal from '@/components/CommonModal'
import CommonTable from '@/components/CommonTable'
import CommonLoading from '@/components/CommonLoading'
import CommonPage from '@/components/CommonPagination';
import DebounceMultipleSelect from '@/components/DebounceMultipleSelect';
import { amountChangeRecord, queryFactoryList } from '../service'
import { formatAmount, customTrimFunc } from '@/utils/utils';
import { getCurrentUser } from '@/utils/authority';
import moment from 'moment';

const { RangePicker } = DatePicker;

const { Option } = Select;

export default ({ handleCancel }) => {

	const [loading, setLoading] = useState(false);//loading

	const [selectLoading, setSLoaing] = useState(false);

	const [data, setData] = useState([]);//表格数据

	const [form] = Form.useForm();

	const [query, setQuery] = useState({});

	const [storeList, setList] = useState([]);

	const [searchKey, setSearchKey] = useState();

	const dateFormat = 'YYYY-MM-DD HH:mm:ss';

	//不能选择以后的时间
	const disabledDate = current => current && current > moment().endOf('day');

	const [pagination, setPagination] = useState({
		current: 1,
		total: 0,
		pageSize: 10,
	})

	useEffect(() => {
		getAmountChangeRecord();
	}, [pagination.current, pagination.pageSize, searchKey])

	//获取金额调整记录
	const getAmountChangeRecord = async () => {
		setLoading(true)
		setData([])
		const params = {
			...query,
			current: pagination.current,
			size: pagination.pageSize,
			uuid: getCurrentUser().uuid,
		}
		if(params.storeId) {
			params.storeId = params.storeId.value;
		}
		if (params.auditTime) {
			params.auditStartTime = moment(params.auditTime[0]).format(dateFormat);
			params.auditEndTime = moment(params.auditTime[1]).format(dateFormat);
			params.auditTime = undefined;
		}
		if (params.applyTime) {
			params.applyStartTime = moment(params.applyTime[0]).format(dateFormat);
			params.applyEndTime = moment(params.applyTime[1]).format(dateFormat);
			params.applyTime = undefined;
		}
		const { success, data } = await amountChangeRecord(params)
		if (success) {
			setData(data.records);
			setPagination({
				...pagination,
				total: data.total
			})
		}
		setLoading(false)
	}

	const columns = [
		{
			title: "门店名称",
			dataIndex: "storeName",
			key: "storeName",
		},
		{
			title: "变更金额",
			children: [
				{
					title: "拿货金额",
					dataIndex: "deductionAmountYuan",
					key: "deductionAmountYuan",
					render: text => text && '¥' + formatAmount(text),
				},
				{
					title: "采购金额",
					dataIndex: "purchaseAmountYuan",
					key: "purchaseAmountYuan",
					render: text => text && '¥' + formatAmount(text),
				},
			]
		},
		{
			title: "变更后金额",
			children: [
				{
					title: "拿货金额",
					dataIndex: "deductionLaterAmountYuan",
					key: "deductionLaterAmountYuan",
					render: text => text && '¥' + formatAmount(text),
				},
				{
					title: "采购金额",
					dataIndex: "purchaseLaterAmountYuan",
					key: "purchaseLaterAmountYuan",
					render: text => text && '¥' + formatAmount(text),
				},
			]
		},
		{
			title: "提交人员",
			dataIndex: "shortName",
			key: "shortName",
		},
		{
			title: "提交时间",
			dataIndex: "applyTime",
			key: "applyTime",
		},
		{
			title: "审核时间",
			dataIndex: "auditTime",
			key: "auditTime",
		},
		{
			title: "审核状态",
			dataIndex: "state",
			key: "state",
			render: text => ['待审核', '已通过', '已拒绝'][text]
		},
	]

	//点击查询
	const handleSearch = val => {
		setQuery(val);
		setPagination({
			...pagination,
			current: 1
		})
		setSearchKey(Date.now());
	}

	//点击重置
	const handleReset = () => {
		setPagination({
			...pagination,
			current: 1
		})
		setQuery({})
		setSearchKey(Date.now());
	}

	//关闭操作
	const onCancel = () => {
		handleCancel()
	}

	//获取供应商列表
	function fetchStoreList(storeName) {
		return new Promise(async (resolve, reject) => {
			setSLoaing(true);
			const params = {
				size: 50,
				current: 1,
				querySrc: 1,
				storeName
			}
			const { data, success } = await queryFactoryList(params);
			setSLoaing(false);
			if (success && data?.records.length) {
				const newArr = [];
				data.records.map((item) => {
					newArr.push({
						label: item.storeName,
						value: item.storeId,
					});
				});
				resolve(newArr);
			} else {
				reject();
			}
		});
	}

	//搜索事件触发
	const handleSearchOption = (value) => {
		fetchStore(value, storeList => setList(value));
	};

	//表格
	const TableProps = {
		data,
		columns
	}

	//分页组件
	const PageProps = {
		pagination,
		handleChange(page, size) {
			setData([]);
			setPagination({
				...pagination,
				current: page,
				pageSize: size
			});
		}
	}

	return <CommonModal
		title="金额调整记录"
		visible={true}
		width='1400px'
		onCancel={onCancel}
		footer={[<Button onClick={onCancel} key='close'>关闭</Button>]}
	>
		<Form
			layout="horizontal"
			className='search-form-style'
			form={form}
			initialValues={{ ...query }}
			onFinish={handleSearch}
			style={{ margin: '12px 0' }}
			autoComplete='off'
		>
			<Form.Item label="门店名称" name="storeId">
				<DebounceMultipleSelect
					showSearch
					placeholder="请输入关键词搜索"
					notFoundContent={selectLoading ? '加载中' : '暂无数据'}
					fetchOptions={fetchStoreList}
					style={{ width: '180px' }}
					allowClear
				/>
			</Form.Item>
			<Form.Item label="提交时间" name="applyTime">
				<RangePicker format={dateFormat} showTime style={{ width: '340px' }} disabledDate={disabledDate} allowClear={false} />
			</Form.Item>
			<Form.Item label="审核时间" name="auditTime">
				<RangePicker format={dateFormat} showTime style={{ width: '340px' }} disabledDate={disabledDate} allowClear={false} />
			</Form.Item>
			<Form.Item>
				<Button type="primary" htmlType="submit">查询</Button>
				<Button htmlType="reset" style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
			</Form.Item>
		</Form>
		<CommonTable {...TableProps} />
		<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '12px' }}>
			<CommonPage {...PageProps} />
		</div>
		<CommonLoading loading={loading} />
	</CommonModal>
}